import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormInstance, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import MyFileUpload from '@/components/MyFileUpload';
import {
  addUserFun,
  getAllRoleFun,
  getUserByIdFun,
  getUserRoleListFun,
  setUserRoleFun,
  updateUserFun,
} from '@/services/ant-design-pro/systemApi';
import { ButtonEnum } from '@/utils/ButtonEnum';
import { message } from 'antd';

const getUserRoles = async (userId) => {
  let res = await getUserRoleListFun(userId);
  return res.data.map((i) => i.roleId);
};

const setUserRole = async (roleIds, userId) => {
  await setUserRoleFun(roleIds, userId);
};

function UserListModal(prop) {
  let { modalVisit, closeModal, selectedUserId, buttonType } = prop;
  let [avatar, setAvatar] = useState('');
  const formRef = useRef<ProFormInstance>();

  useEffect(() => {
    if (selectedUserId && modalVisit) {
      getUserByIdFun(selectedUserId).then(async (res) => {
        let roleIds = await getUserRoles(selectedUserId);
        formRef?.current?.setFieldsValue({
          ...res.data,
          roleIds,
        });
        setAvatar(res.data.avatar);
      });
    } else {
      setAvatar('');
    }
  }, [modalVisit]);

  const fileChange = (list) => {
    setAvatar(list.map((i) => i.url).join(','));
  };

  // 点击保存触发
  const onFinish = async (values) => {
    let data = {
      ...values,
      avatar,
      nickName: values.userName,
    };
    if (buttonType === ButtonEnum.ADD) {
      addUserFun(data).then((res) => {
        message.success(res.msg);
        closeModal(true);
      });
    } else {
      updateUserFun({
        ...data,
        userId: selectedUserId,
      }).then(async (res) => {
        await setUserRole(data.roleIds, selectedUserId);
        message.success(res.msg);
        closeModal(true);
      });
    }
  };

  const getRoleList = async () => {
    let res = await getAllRoleFun({});
    return res.data.map((item) => {
      return {
        label: item.roleName,
        value: item.roleId,
      };
    });
  };

  return (
    <>
      <ModalForm
        formRef={formRef}
        title="新建用户"
        open={modalVisit}
        onFinish={onFinish}
        width={'600px'}
        layout={'vertical'}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => closeModal(false),
        }}
      >
        <ProFormText
          name="userName"
          label="用户名称"
          tooltip="长度大于6位"
          placeholder="请输入用户名称"
          rules={[{ required: true, message: '请输入用户名称' }]}
        />

        <ProFormText
          name="email"
          label="用户邮箱"
          placeholder="请输入用户邮箱"
          rules={[{ type: 'email', message: '请输入正确的邮箱格式' }]}
        />

        <ProFormText name="phonenumber" label="用户手机号码" placeholder="请输入用户手机号码" />

        <ProFormSelect
          name="sex"
          label="性别"
          request={async () => [
            { label: '男', value: '0' },
            { label: '女', value: '1' },
            { label: '未知', value: '2' },
          ]}
          placeholder="请选择性别"
          rules={[{ required: true, message: '请选择性别' }]}
        />

        {buttonType !== ButtonEnum.ADD && (
          <ProFormSelect
            name="roleIds"
            label="分配角色"
            request={getRoleList}
            placeholder="请分配角色"
            mode="multiple"
            rules={[{ required: true, message: '请分分配角色' }]}
          />
        )}

        <MyFileUpload label={'头像'} name={'avatar'} value={avatar} onChange={fileChange} />
      </ModalForm>
    </>
  );
}

export default UserListModal;
